package com.yimingkeji.mongo.rest;

import com.mongodb.BasicDBObject;
import com.yimingkeji.mongo.dao.UserRepository;
import com.yimingkeji.mongo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;
import java.util.List;

/**
 * @Describe:
 * @Auther: zhenlong.yang
 * @Date: 2018/12/4 13:23
 */
@RestController
public class UserResource {

    /**------------ MongoTemplate CURD -------------*/
    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("/template/user")
    public User save(@RequestBody User user){
        return mongoTemplate.save(user);
    }

    @GetMapping("/template/user")
    public List<User> findAll(){
        return mongoTemplate.findAll(User.class);
    }

    @GetMapping("/template/user/{name}")
    public User findOne(@PathVariable String name){
        return mongoTemplate.findOne(Query.query(Criteria.where("name").is(name)), User.class);
    }

    /**------------ MongoTemplate 聚合统计 -------------*/

    /**根据自定义字段分组统计*/
    @GetMapping("/template/group/{groupFiled}")
    public Iterator<BasicDBObject> groupBase(@PathVariable String groupFiled){
        Aggregation agg = Aggregation.newAggregation(Aggregation.group(groupFiled).count().as("总人数"));
        AggregationResults<BasicDBObject> res = mongoTemplate.aggregate(agg, "stu", BasicDBObject.class);
        Iterator<BasicDBObject> iterator = res.iterator();
        return iterator;
    }

    /**按条件，根据多个字段分组*/
    @GetMapping("/template/group")
    public Iterator<BasicDBObject> groupWithQueryCondition(){
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("age").gte(10)),
                Aggregation.group("school", "grade").count().as("总人数"),
                Aggregation.project("总人数").and("分组字段").previousOperation()//显示分组字段，不显示_id
        );
        AggregationResults<BasicDBObject> res = mongoTemplate.aggregate(agg, "stu", BasicDBObject.class);
        Iterator<BasicDBObject> iterator = res.iterator();
        return iterator;
    }

    /**------------ MongoRepository -------------*/
    @Autowired private UserRepository userRepository;
    @PostMapping("/repository/user")
    public User save1(@RequestBody User user){
        return userRepository.save(user);
    }

    @GetMapping("/repository/user")
    public List<User> findAll1(){
        return userRepository.findAll();
    }

    @GetMapping("/repository/user/{name}")
    public User findOne1(@PathVariable String name){
        return userRepository.findByName(name);
    }

}
